── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ readr::col_factor() masks scales::col_factor()
✖ purrr::discard() masks scales::discard()
✖ dplyr::filter() masks stats::filter()
✖ stringr::fixed() masks recipes::fixed()
✖ dplyr::lag() masks stats::lag()
✖ readr::spec() masks yardstick::spec()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(tsibble)
Warning: package 'tsibble' was built under R version 4.4.3
Registered S3 method overwritten by 'tsibble':
method from
as_tibble.grouped_df dplyr
Attaching package: 'tsibble'
The following object is masked from 'package:lubridate':
interval
The following objects are masked from 'package:base':
intersect, setdiff, union
# Example: Cache la Poudre River at Mouth (USGS site 06752260)poudre_flow <-readNWISdv(siteNumber ="06752260", # Download data from USGS for site 06752260parameterCd ="00060", # Parameter code 00060 = discharge in cfs)startDate ="2013-01-01", # Set the start dateendDate ="2023-12-31") |># Set the end daterenameNWISColumns() |># Rename columns to standard names (e.g., "Flow", "Date")mutate(Date =yearmonth(Date)) |># Convert daily Date values into a year-month format (e.g., "2023 Jan")group_by(Date) |># Group the data by the new monthly Datesummarise(Flow =mean(Flow)) # Calculate the average daily flow for each month
# Convert to tsibble (monthly data, with Date as index)poudre_ts <- poudre_flow |>as_tsibble(index = Date)
2. Plotting the time series
library(ggplot2)library(plotly)
Warning: package 'plotly' was built under R version 4.4.3
Attaching package: 'plotly'
The following object is masked from 'package:ggplot2':
last_plot
The following object is masked from 'package:stats':
filter
The following object is masked from 'package:graphics':
layout
# Basic ggplot of flow over timep <-ggplot(poudre_ts, aes(x = Date, y = Flow)) +geom_line(color ="navyblue") +labs(title ="Monthly Average Flow of Cache la Poudre River",y ="Flow (cfs)", x ="Date") +theme_minimal()# Animate with plotlyggplotly(p)
3. Subseries
library(feasts)
Warning: package 'feasts' was built under R version 4.4.3
Loading required package: fabletools
Warning: package 'fabletools' was built under R version 4.4.3
Attaching package: 'fabletools'
The following object is masked from 'package:yardstick':
accuracy
The following object is masked from 'package:parsnip':
null_model
The following objects are masked from 'package:infer':
generate, hypothesize
# use gg_subseries to visualize the datasubseries_plot <- poudre_ts %>%gg_subseries(Flow) +labs(title ="Monthly Subseries of Poudre River Flow") +theme_minimal()print(subseries_plot)
4. Decompose
library(fabletools)# STL decomposition with a seasonal window (say 13 months for annual seasonality)decomp <- poudre_ts |>model(STL(Flow ~season(window ="periodic"))) |>components()# Plot the componentsautoplot(decomp)